/**
 * @file YzhTeachers.vue
 * @description 教师管理主页面组件 - 使用yzh前缀表格
 * @created 2024-07-15
 */

<template>
  <div class="teachers-container">
    <div class="header">
      <h1>教师管理</h1>
      <div class="header-actions">
        <button class="import-btn" @click="showImportDialog">导入教师</button>
        <button class="export-btn" @click="exportTeachers">导出教师</button>
        <button class="add-btn" @click="showAddTeacherDialog">+ 添加教师</button>
      </div>
    </div>

    <!-- 加载状态显示 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载教师数据中...</div>
    </div>

    <!-- 空数据状态 -->
    <div v-else-if="collegesData.length === 0" class="empty-data">
      暂无教师数据，请添加教师
    </div>

    <!-- 学院和教师数据 -->
    <div v-else v-for="college in collegesData" :key="college.id" class="college-section">
      <div class="college-header">
        <h2>{{ college.name }}</h2>
        <span class="teacher-count">教师数: {{ getTotalTeachers(college) }}</span>
        </div>
        
      <!-- 遍历学院下的系部 -->
      <div v-for="department in college.departments" 
           :key="department.name" 
           class="department-section">
        <h3>{{ department.name }}</h3>
        <div class="teacher-grid">
          <!-- 遍历系部下的教师 -->
          <div v-for="teacher in department.teachers" 
               :key="teacher.id" 
               class="teacher-card">
                  <div class="teacher-avatar" @click="viewTeacherDetail(teacher)">
                    <span v-if="teacher.gender === '女'">👩‍🏫</span>
                    <span v-else>👨‍🏫</span>
                  </div>
                  <div class="teacher-info" @click="viewTeacherDetail(teacher)">
                    <h4>{{ teacher.name }}</h4>
                    <p>{{ teacher.title || '未设置职称' }}</p>
              <p class="teacher-code">工号: {{ teacher.teacher_code }}</p>
                  </div>
                  <div class="teacher-actions">
                    <button class="action-btn edit-btn" @click="editTeacher(teacher)">
                      编辑
                    </button>
                    <button class="action-btn delete-btn" @click="confirmDeleteTeacher(teacher)">
                      删除
                    </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 教师表单模态框 -->
    <TeacherFormModal 
      v-if="showTeacherForm" 
      :is-edit="isEditMode"
      :teacher-data="currentTeacher"
      :colleges="colleges"
      :departments="departments"
      @close="closeTeacherForm"
      @submit="handleTeacherSubmit"
    />
    
    <!-- 确认删除对话框 -->
    <ConfirmDialog
      v-if="showDeleteConfirm"
      title="确认删除"
      message="确定要删除此教师吗？此操作不可恢复。"
      confirm-text="删除"
      @confirm="deleteTeacher"
      @cancel="cancelDelete"
    />
  </div>
</template>

<script setup>
/**
 * 教师管理组件
 * @description 显示和管理教师列表，支持添加、编辑、删除教师
 */
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getTeacherList, addTeacher, updateTeacher, deleteTeacher as apiDeleteTeacher, getColleges, getDepartments } from '@/api/admin/yzhTeacher'
import TeacherFormModal from '@/components/Manage/TeacherFormModal.vue'
import ConfirmDialog from '@/components/Manage/ConfirmDialog.vue'

const router = useRouter()
const loading = ref(false)

// 教师数据
const allTeachers = ref([])
const colleges = ref([])
const departments = ref([])
const collegesData = ref([])

// 模态框控制
const showTeacherForm = ref(false)
const showDeleteConfirm = ref(false)
const isEditMode = ref(false)
const currentTeacher = ref(null)

// 计算学院总教师数
const getTotalTeachers = (college) => {
  return college.departments.reduce((total, dept) => total + dept.teachers.length, 0)
}

// 显示添加教师对话框
const showAddTeacherDialog = () => {
  isEditMode.value = false
  currentTeacher.value = {
    name: '',
    teacher_code: '',
    title: '',
    college_id: '',
    department_id: '',
    gender: '',
    email: '',
    phone: ''
  }
  showTeacherForm.value = true
}

// 编辑教师信息
const editTeacher = (teacher) => {
  isEditMode.value = true
  currentTeacher.value = { ...teacher }
  showTeacherForm.value = true
}

// 查看教师详情
const viewTeacherDetail = (teacher) => {
  // 跳转到教师详情页面
  router.push(`/admin/teacher/${teacher.id}`)
}

// 关闭教师表单
const closeTeacherForm = () => {
  showTeacherForm.value = false
}

// 确认删除教师
const confirmDeleteTeacher = (teacher) => {
  currentTeacher.value = { ...teacher }
  showDeleteConfirm.value = true
}

// 取消删除
const cancelDelete = () => {
  showDeleteConfirm.value = false
}

// 删除教师
const deleteTeacher = async () => {
  try {
    const res = await apiDeleteTeacher(currentTeacher.value.id)
    if (res.status === 'success') {
      // 关闭确认框
      showDeleteConfirm.value = false
      // 重新加载教师列表
      fetchTeachers()
    } else {
      alert(`删除失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('删除教师失败:', error)
    alert('删除教师失败，请稍后重试')
  }
}

// 处理教师表单提交
const handleTeacherSubmit = async (formData) => {
  try {
    let res
    
    if (isEditMode.value) {
      // 更新教师
      res = await updateTeacher(formData.id, formData)
    } else {
      // 添加教师
      res = await addTeacher(formData)
    }
    
    if (res.status === 'success') {
      // 关闭表单
      showTeacherForm.value = false
      // 重新加载教师列表
      fetchTeachers()
    } else {
      alert(`操作失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('提交教师数据失败:', error)
    alert('提交失败，请稍后重试')
  }
}

// 导入教师
const showImportDialog = () => {
  alert('导入功能尚未实现')
}

// 导出教师
const exportTeachers = () => {
  alert('导出功能尚未实现')
}

// 根据college_id获取学院名称
const getCollegeName = (collegeId) => {
  if (!collegeId) return '未分配'
  const college = colleges.value.find(item => item.id === collegeId)
  return college ? college.name : '未知学院'
}

// 根据department_id获取系部名称
const getDepartmentName = (departmentId) => {
  if (!departmentId) return '未分配'
  const department = departments.value.find(item => item.id === departmentId)
  return department ? department.name : '未知系部'
}

// 获取所有教师并分组展示
const fetchTeachers = async () => {
  loading.value = true
  try {
    // 获取教师列表
    const res = await getTeacherList()
    
    if (res.status === 'success' && res.data && res.data.teachers) {
      allTeachers.value = res.data.teachers.map(teacher => ({
        ...teacher,
        college_id: parseInt(teacher.college_id || 0),
        department_id: parseInt(teacher.department_id || 0)
      }))
      
      console.log(`加载了 ${allTeachers.value.length} 位教师数据`)
      
      // 组织数据为学院-系部-教师的层级结构
      const tempCollegesData = {}
      
      // 先将所有学院整理成正确格式
      colleges.value.forEach(college => {
        tempCollegesData[college.id] = {
          id: college.id,
          name: college.name,
          departments: {}
        }
      })
      
      // 为各学院添加系部
      departments.value.forEach(dept => {
        if (tempCollegesData[dept.college_id]) {
          if (!tempCollegesData[dept.college_id].departments[dept.id]) {
            tempCollegesData[dept.college_id].departments[dept.id] = {
              id: dept.id,
              name: dept.name,
              teachers: []
            }
          }
        }
      })
      
      // 将教师分配到相应的学院和系部
      allTeachers.value.forEach(teacher => {
        const collegeId = teacher.college_id
        const departmentId = teacher.department_id
        
        if (collegeId && departmentId && tempCollegesData[collegeId] && tempCollegesData[collegeId].departments[departmentId]) {
          tempCollegesData[collegeId].departments[departmentId].teachers.push(teacher)
        } else {
          console.warn(`教师 ${teacher.name} (ID: ${teacher.id}) 的学院或系部数据有误`)
        }
      })
      
      // 转换为数组格式供模板使用
      collegesData.value = Object.values(tempCollegesData)
        .filter(college => Object.keys(college.departments).length > 0)
        .map(college => ({
          id: college.id,
          name: college.name,
          departments: Object.values(college.departments)
            .filter(dept => dept.teachers && dept.teachers.length > 0)
        }))
      
      console.log(`处理完成: ${collegesData.value.length} 个学院数据`)
    } else {
      console.error('获取教师列表失败:', res)
      allTeachers.value = []
      collegesData.value = []
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
    allTeachers.value = []
    collegesData.value = []
  } finally {
    loading.value = false
  }
}

// 获取所有学院
const fetchColleges = async () => {
  try {
    const res = await getColleges()
    if (res.status === 'success' && res.data && res.data.colleges) {
      colleges.value = res.data.colleges
      console.log(`YzhTeachers.vue: 加载了 ${colleges.value.length} 个学院数据`)
      console.log('YzhTeachers.vue: 学院数据详情:', JSON.stringify(colleges.value, null, 2)) // 详细打印学院数据
    } else {
      console.error('YzhTeachers.vue: 获取学院列表失败:', res)
      colleges.value = []
    }
  } catch (error) {
    console.error('YzhTeachers.vue: 获取学院列表异常:', error)
    colleges.value = []
  }
}

// 获取所有系部
const fetchAllDepartments = async () => {
  try {
    const allDepartments = []
    
    // 逐个获取每个学院的系部
    for (const college of colleges.value) {
      try {
        const res = await getDepartments(college.id)
        if (res.status === 'success' && res.data && res.data.departments) {
          // 添加college_id属性
          const depts = res.data.departments.map(dept => ({
            ...dept,
            college_id: college.id
          }))
          allDepartments.push(...depts)
        }
      } catch (error) {
        console.error(`获取学院 ${college.name} (ID: ${college.id}) 的系部列表失败:`, error)
      }
    }
    
    departments.value = allDepartments
    console.log(`加载了 ${departments.value.length} 个系部数据`)
  } catch (error) {
    console.error('获取系部列表失败:', error)
    departments.value = []
  }
}

// 页面加载时获取数据
onMounted(async () => {
  // 按顺序加载数据
  await fetchColleges()
  await fetchAllDepartments()
  await fetchTeachers()
})
</script>

<style scoped>
.teachers-container {
  padding: 30px;
  background: #f5f6fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #1a1a1a;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.add-btn {
  padding: 10px 20px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.import-btn, .export-btn {
  padding: 10px 15px;
  background: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.add-btn:hover {
  background: #40a9ff;
}

.import-btn:hover, .export-btn:hover {
  background: #e6f7ff;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: #666;
  font-size: 16px;
}

.empty-data {
  text-align: center;
  padding: 50px;
  color: #999;
  font-size: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.college-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
  overflow: hidden;
}

.college-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f0f7ff;
  border-bottom: 1px solid #eaeaea;
}

.college-header h2 {
  margin: 0;
  font-size: 18px;
  color: #1a1a1a;
}

.teacher-count {
  font-size: 14px;
  color: #666;
  background: #e6f7ff;
  padding: 4px 10px;
  border-radius: 4px;
}

.department-section {
  padding: 20px;
}

.department-section h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.teacher-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

.teacher-card {
  border: 1px solid #eaeaea;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s;
}

.teacher-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.teacher-avatar {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  background: #f0f7ff;
  font-size: 42px;
  cursor: pointer;
}

.teacher-info {
  padding: 15px;
  cursor: pointer;
}

.teacher-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.teacher-info p {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #666;
}

.teacher-code {
  color: #1890ff;
  font-size: 12px;
}

.teacher-actions {
  display: flex;
  border-top: 1px solid #f0f0f0;
}

.action-btn {
  flex: 1;
  padding: 10px 0;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.edit-btn {
  color: #1890ff;
}

.delete-btn {
  color: #ff4d4f;
}

.edit-btn:hover {
  background: #e6f7ff;
}

.delete-btn:hover {
  background: #fff1f0;
}
</style> 